﻿using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;

namespace Sigil.Impl
{
	// Just a dinky little class to automatically generate names for things like methods, labels, and locals
	internal static class AutoNamer
	{
		private static readonly Object NullKey = new Object();
		private static readonly ConcurrentDictionary<Tuple<Object, String>, Int32> State = new ConcurrentDictionary<Tuple<Object, String>, Int32>();

		public static String Next(String root)
		{
			return Next(NullKey, root);
		}

		public static String Next(Object on, String root, params IEnumerable<String>[] inUse)
		{
			var key = Tuple.Create(on, root);

			//lock (State)
			//{
			Int32 next;
			if (!State.TryGetValue(key, out next))
			{
				next = 0;
				State[key] = next;
			}

			State[key]++;

			var ret = root + next;

			if (inUse.Any(a => a.Any(x => x == ret)))
			{
				return Next(on, root, inUse);
			}

			return ret;
			//}
		}

		public static void Release(Object on)
		{
			//lock (State)
			//{
			var deadKeys = State.Keys.Where(k => k.Item1 == on);

			foreach (var key in deadKeys)
			{
				Int32 v;
				State.TryRemove(key, out v);
			}
			//}
		}
	}
}